package org.eclipse.football.web;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class GetDataFromURL {

	/**
	 * reads in data from cbssports.com and creates a local copy of the data for
	 * parsing
	 * 
	 * @param week
	 *            what week we want the data from
	 * @param stat
	 *            : rushing, receiving, passing, kicking
	 * @throws IOException
	 */
	public static void getData(String week, String stat) throws IOException {
		URL url = new URL(
				"http://www.cbssports.com/nfl/stats/leaders/live/all/" + stat
						+ "/week" + week);
		try {
			url.openConnection();
			// System.out.println(url.toString());
			BufferedWriter buffwrite = null;
			buffwrite = new BufferedWriter(new FileWriter(stat + week + ".txt"));
			buffwrite.append(getURLContent(url));
			if (buffwrite != null) {
				try {
					buffwrite.flush();
					buffwrite.close();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	public static void getDefData() throws IOException {
		URL url = new URL("http://espn.go.com/nfl/schedule");
		try {
			url.openConnection();
			//System.out.println(url.toString());
			BufferedWriter buffwrite = null;
			buffwrite = new BufferedWriter(new FileWriter("def.txt"));
			buffwrite.append(getURLContent(url));
			if (buffwrite != null) {
				try {
					buffwrite.flush();
					buffwrite.close();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	/**
	 * takes a url and gets the page source in a CharSequence
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public static CharSequence getURLContent(URL url) throws IOException {
		URLConnection connection = url.openConnection();
		String encoding = connection.getContentEncoding();
		if (encoding == null) {
			encoding = "UTF-8";
		}
		BufferedReader buffread = new BufferedReader(new InputStreamReader(
				connection.getInputStream(), encoding));
		StringBuilder result = new StringBuilder();
		try {
			String line;
			while ((line = buffread.readLine()) != null) {
				result.append(line + '\n');
			}
		} finally {
			buffread.close();
		}
		return result;
	}
}
